from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from utils.mixins import *
from utils.viewsets import *
from utils.response import SuccessResponse

from apps.HttpTestcase.models import Module
from apps.HttpTestcase.filters.module import ModuleFilters
from apps.HttpTestcase.serializers import ModuleFindModeSerializer, ModuleCreadModeSerializer, ModuleListModeSerializer


class ModularListViewSet(ReadOnlyModelViewSet):
    perms_map = {'get': '*'}
    filter_class = ModuleFilters
    queryset = Module.objects.filter(is_delete=False)
    serializer_class = ModuleListModeSerializer


class ModularViewSet(CreateModelMixin, UpdateModelMixin, DestroyModelMixin, GenericViewSet):
    queryset = Module.objects.filter(is_delete=False)
    serializer_class = ModuleCreadModeSerializer
    perms_map = {'get': '*', 'post': 'module_create',
                 'put': 'module_update', 'delete': 'module_delete'}

    def create(self, request, *args, **kwargs):
        data = request.data
        parent = data.get('parent')
        if parent:
            parent_module = Module.objects.filter(id=parent, is_delete=False).first()
            if parent_module.floor == 4:
                return Response(200, None, '模块创建失败，原因：模块层级最多为4层！')
            else:
                data['floor'] = parent_module.floor + 1
        else:
            data['floor'] = 1

        response = super().create(request, *args, **kwargs)
        return SuccessResponse(data=response.data, msg='创建成功！')

    def perform_destroy(self, instance):
        instance.is_delete = True
        instance.save()  # 逻辑删除

    # 根据项目ID查询模块
    @action(methods=['post'], detail=True)
    def findmodule(self, request, *args, **kwargs):

        id = request.data.get('projectId')  # 获取参数

        if id is not '':
            # __contains模糊查询
            queryset = Module.objects.filter(project=id).filter(is_delete=False)
        else:
            queryset = self.filter_queryset(self.get_queryset())
        serializer = ModuleCreadModeSerializer(queryset, many=True)
        return SuccessResponse(data={'data':serializer.data}, msg='查询成功！')
